import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const routes = [
  {
    path: '/', name: 'MainLayout', component: () => import('@/views/MainLayout.vue'), redirect:'/index',
    children: [
      { path: 'index', component: () => import('@/views/Index.vue') },
      { path: 'management', component: () => import('@/views/Management.vue') },
      { path: 'blacklist', component: () => import('@/views/BlackList.vue') },
      { path: 'tempRule', component: () => import('@/views/BillTempRule.vue') },
      { path: 'longRule', component: () => import('@/views/BillLongRule.vue') },
      { path: 'userParkCard', component: () => import('@/views/UserParkCard.vue') },
      { path: 'parkCard', component: () => import('@/views/UserParkCard.vue') },
      { path: 'parkRecord', component: () => import('@/views/ParkRecord.vue') },
      { path: 'payRecord', component: () => import('@/views/PayRecord.vue') },
      { path: 'admin', component: () => import('@/views/Admin.vue') },
      { path: 'operationLog', component: () => import('@/views/OperationLog.vue') },
    ]
  },
  { path: '/login', component: () => import('@/views/Login.vue') },
  { path: '/:pathMatch(.*)*', name: 'NotFound', component: () => import('@/views/404.vue') }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  authStore.initializeAuth()

  // 如果未登录且目标不是登录页，重定向到登录页
  if (to.path !== '/login' && !authStore.isAuthenticated()) {
    next('/login')
  }
  // 如果已登录且目标是登录页，重定向到首页
  else if (to.path === '/login' && authStore.isAuthenticated()) {
    next('/')
  }
  // 其他情况正常跳转（包括404页面）
  else {
    next()
  }
})

export default router
